package com.lyz.tool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolUtils {

    private ThreadPoolUtils() {}

    /**
     * @param pool               需要优雅关闭的线程池
     * @param shutDownTimeOut    shutDown命令的超时时间
     * @param shutDownNowTimeOut shutDownNow命令的超时时间(表示线程池关闭有问题)
     * @param timeUnit           超时的时间单位
     */
    public static void shutDownPool(ExecutorService pool, int shutDownTimeOut,
                                    int shutDownNowTimeOut, TimeUnit timeUnit) {
        pool.shutdown();
        try {
            // 等待了一段时间，发现线程池仍然没有被关闭
            if (!pool.awaitTermination(shutDownTimeOut, timeUnit)) {
                pool.shutdownNow();
                if (!pool.awaitTermination(shutDownNowTimeOut, timeUnit)) {
                    // 强关都没有关掉，应该是有问题了
                    log.error("ThreadPoolUtils.shutDownPool.error");
                }
            }
        } catch (InterruptedException e) {
            // 外部线程被打断了，就会抛出该打断异常
            log.error("ThreadPoolUtils.shutDownPool.interrupt.error:{}", e.getMessage(), e);
            // 直接把线程池关闭
            pool.shutdownNow();
            // 直接将当前关闭线程给中断
            Thread.currentThread().interrupt();
        }
    }

}
